using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace Zsa.Emulation.Util
{
    /// <summary>
    /// A generic wrapper for weak reference.  Used to keep a reference to a class while still
    /// allowing it to be garbage collected.  
    /// </summary>
    /// <typeparam name="TObj">The object type.</typeparam>
    [StructLayout(LayoutKind.Sequential)]
    public struct GenericWeakReference<TObj> : IGenericWeakReference<TObj> 
        where TObj : class
    {
        #region Static Methods

        /// <summary>
        /// Creates a new instance of the <see cref="GenericWeakReference&lt;TObj&gt;"/> class.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <returns></returns>
        public static GenericWeakReference<TObj> Create(TObj obj)
        {
            return Create(
                obj,
                GCHandleType.Weak,
                PersistReferenceType.Release
            );

        }

        /// <summary>
        /// Creates a new instance of the <see cref="GenericWeakReference&lt;TObj&gt;"/> class.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <param name="initialReference">The initial reference.</param>
        /// <returns></returns>
        public static GenericWeakReference<TObj> Create(TObj obj,
            PersistReferenceType initialReference)
        {
            return Create(
                obj,
                GCHandleType.Weak,
                initialReference
            );

        }

        /// <summary>
        /// Creates a new instance of the <see cref="GenericWeakReference&lt;TObj&gt;"/> class.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <param name="gcHandleType">Type of the gc handle.</param>
        /// <returns></returns>
        public static GenericWeakReference<TObj> Create(TObj obj,
            GCHandleType gcHandleType)
        {
            return Create(
                obj,
                gcHandleType,
                PersistReferenceType.Release
            );

        }

        /// <summary>
        /// Creates a new instance of the <see cref="GenericWeakReference&lt;TObj&gt;"/> class.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <param name="gcHandleType">Type of the gc handle.</param>
        /// <param name="initialReference">The initial reference.</param>
        /// <returns></returns>
        public static GenericWeakReference<TObj> Create(TObj obj,
            GCHandleType gcHandleType, PersistReferenceType initialReference)
        {
            // Check for null object.
            if (obj == null)
            {
                throw new ArgumentNullException("obj", "obj cannnot be null !");
            }
            // The handle type must be weak or weak tracked.
            if (gcHandleType != GCHandleType.Weak && gcHandleType != GCHandleType.WeakTrackResurrection)
            {
                throw new ArgumentOutOfRangeException("gcHandleType",
                    gcHandleType, "The GC handle parameter can only only be WeakReference or WeakTrackReference !");
            }
            //The initial reference type must be acquired or not acquired.
            int _Temp = (int)initialReference;
            if ((_Temp & 2) == 0)
            {
                throw new ArgumentOutOfRangeException("initialReference",
                    _Temp, "The persist mode is invalid !");
            }
            //Create the handle.
            GCHandle _Handle = GCHandle.Alloc(obj, gcHandleType);
            //Return the wrapper.
            return new GenericWeakReference<TObj>(
                obj,
                _Handle
                );
        }

        #endregion Static Methods

        #region Fields
        /// <summary>
        /// The handle.
        /// </summary>
        private GCHandle _Handle;

        /// <summary>
        /// Strong reference to the object.
        /// </summary>
        private TObj _StrongReference;
        #endregion Fields

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="GenericWeakReference&lt;TObj&gt;"/> class.
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <param name="handle">The handle.</param>
        private GenericWeakReference(TObj obj,
            GCHandle handle)
        {
            _Handle = handle;
            _StrongReference = obj;
        }

        #endregion Constructor

        #region Properties

        /// <summary>
        /// Gets a value indicating whether this instance is alive.
        /// </summary>
        /// <value><c>true</c> if this instance is alive; otherwise, <c>false</c>.</value>
        public bool IsAlive
        {
            get
            {
                return _Handle.IsAllocated;
            }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is empty.
        /// </summary>
        /// <value><c>true</c> if this instance is empty; otherwise, <c>false</c>.</value>
        public bool IsEmpty
        {
            get
            {
                return _Handle.AddrOfPinnedObject() == IntPtr.Zero;
            }
        }

        /// <summary>
        /// Gets the address.
        /// </summary>
        /// <value>The address.</value>
        public IntPtr Address
        {
            get
            {
                return _Handle.AddrOfPinnedObject();
            }
        }

        /// <summary>
        /// Gets the target.
        /// </summary>
        /// <value>The target.</value>
        public TObj Target
        {
            get
            {
                if (_StrongReference == null)
                {
                    return InternalTarget;
                }
                else
                {
                    return _StrongReference;
                }
            }
        }

        /// <summary>
        /// Gets the internal target.
        /// </summary>
        /// <value>The internal target.</value>
        internal TObj InternalTarget
        {
            get
            {
                try
                {
                    return _Handle.Target as TObj;
                }
                catch(InvalidOperationException)
                {
                    return null;
                }
            }
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Attempts to get a reference to the object.
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <returns></returns>
        public bool TryGetReference(out TObj obj)
        {
            return TryGetReference(PersistReferenceType.None, out obj);
        }

        /// <summary>
        /// Attempts to get a reference to the object.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <param name="obj">address of variable to put obj in</param>
        /// <returns><c>true</c> if this instance is alive; otherwise, <c>false</c>.</returns>
        public bool TryGetReference(PersistReferenceType persist,
            out TObj obj)
        {
            // Get the internal strong reference first.
            obj = _StrongReference;

            // Check to see if the strong reference is null.
            if (obj != null)
            {
                // If persist set to release then release the internal strong ref.
                if (persist == PersistReferenceType.Release)
                {
                    _StrongReference = null;
                }
                return true;
            }
            // Try to get the obj from the handle.
            obj = InternalTarget;

            // If obj is null return false.
            if (obj == null)
            {
                return false;
            }

            // If set to persist then set the local var to the ref.
            if (persist == PersistReferenceType.Acquire)
            {
                _StrongReference = obj;
            }
            return true;
        }

        /// <summary>
        /// Releases the strong reference.
        /// </summary>
        public void ReleaseStrongReference()
        {
            if (IsEmpty)
            {
                return;
            }
            _StrongReference = null;
        }

        /// <summary>
        /// Accquires the strong reference.
        /// </summary>
        /// <returns></returns>
        public bool AccquireStrongReference()
        {
            if (_StrongReference != null)
            {
                return true;
            }
            _StrongReference = InternalTarget;
            return _StrongReference != null;
        }

        /// <summary>
        /// Releases the Gc handle
        /// </summary>
        public void Free()
        {
            _StrongReference = null;
            try
            {
                _Handle.Free();
            }
            catch (InvalidOperationException) { _Handle = new GCHandle(); }
        }

        #region Object Overloads
        /// <summary>
        /// Indicates whether this instance and a specified object are equal.
        /// </summary>
        /// <param name="obj">Another object to compare to.</param>
        /// <returns>
        /// true if obj and this instance are the same type and represent the same value; otherwise, false.
        /// </returns>
        public override bool Equals(object obj)
        {
            return _Handle.Equals(obj);
        }

        /// <summary>
        /// Returns the hash code for this instance.
        /// </summary>
        /// <returns>
        /// A 32-bit signed integer that is the hash code for this instance.
        /// </returns>
        public override int GetHashCode()
        {
            return _Handle.GetHashCode();
        }

        /// <summary>
        /// Returns the fully qualified type name of this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.String"></see> containing a fully qualified type name.
        /// </returns>
        public override string ToString()
        {
            if (IsAlive)
            {
                return string.Format(
                    "Reference Address : {0}.  Type : {0}",
                    this.Address,
                    typeof(TObj).ToString()
                    );
            }
            else
            {
                return string.Format(
                    "Dead Reference. Type : {0}",
                    this.Address
                    );
            }
        }
        #endregion Object Overloads

        #endregion Methods
    }

    /// <summary>
    /// Indicates if the reference is to be acquired or reaquired.
    /// </summary>
    public enum PersistReferenceType : byte
    {
        /// <summary>
        /// None.
        /// </summary>
        None = 0,
        /// <summary>
        /// Keeps a typed reference to prevent the gc from collecting.        
        /// </summary>
        Acquire = 1,
        /// <summary>
        /// Releases the current reference so it can be gc'ed.
        /// </summary>
        Release = 2
    }
}
